package com.lagou.studentsystem.servlet;


import com.lagou.studentsystem.model.Student;
import com.lagou.studentsystem.model.User;
import com.lagou.studentsystem.service.StudentService;
import com.lagou.studentsystem.service.UserService;
import com.lagou.studentsystem.service.impl.StudentServiceImpl;
import com.lagou.studentsystem.service.impl.UserServiceImp;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");

        UserService userService = new UserServiceImp();
        User user = userService.userLoginService(new User(userName, passWord));

        Cookie username = new Cookie("username", userName);
        username.setMaxAge(20);
        response.addCookie(username);
        Cookie password = new Cookie("password", passWord);
        password.setMaxAge(20);
        response.addCookie(password);

        if (null != user) {
            request.getSession().setAttribute("user", user);
            RequestDispatcher findAllStudent = request.getRequestDispatcher("findStudentAll");
            findAllStudent.forward(request, response);
        } else {
            response.sendRedirect("login.html");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
